package com.xqh.study.springtxjta.service;

import com.xqh.study.springtxjta.dao.CustomerRepository;
import com.xqh.study.springtxjta.domain.Customer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName CustomerServiceInAnnotation
 * @Description 注解方式实现事务管理
 * @Author xuqianghui
 * @Date 2019/12/30 21:29
 * @Version 1.0
 */
@Service
@Slf4j
public class CustomerServiceInAnnotation {

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Transactional
    public Customer create(Customer customer){
        customer.setUsername("Annotation:"+customer.getUsername());
        customerRepository.save(customer);
        jmsTemplate.convertAndSend("customer:msg:reply", customer.getUsername());
        return customer;
    }

    @JmsListener(destination = "customer:msg1:new")
    @Transactional
    public void create(String name){
        log.info("create customer by listen . name ==>{}", name);
        Customer customer = new Customer();
        customer.setUsername("Annotation-listen: "+name);
        customer.setPassword("123456");
        customer.setRole("jms customer");
        customerRepository.save(customer);
        jmsTemplate.convertAndSend("customer:msg:reply", customer.getUsername());
        if(1 ==1){
            throw new RuntimeException("some error happen.");
        }
    }
}
